<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- alert警示条 -->
      <el-row>
        <el-col>
          <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
        </el-col>
      </el-row>
      <!-- 步骤条区域 -->
      <!-- active绑定的值是数字型 但是传过来的值是字符串 所以需要-0进行隐式转换 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <!-- 侧边栏导航 -->
      <el-form
        :model="tabFromList"
        :rules="tabFromListRules"
        ref="tabFromListRef"
        label-width="100px"
        label-position="top"
      >
        <!-- name是v-nodel绑定的选中选项卡的值 是字符串类型 -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="活动名称" prop="goods_name">
              <el-input v-model="tabFromList.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price" type="number">
              <el-input v-model="tabFromList.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" type="number">
              <el-input v-model="tabFromList.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number">
              <el-input v-model="tabFromList.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="tabFromList.goods_cat"
                :options="cataList"
                :props="cateProps"
                @change="handleCascaderChange"
                clearable
                width="100%"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyTabList" :key="item.attr_id" :label="item.attr_name">
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item"
                  v-for="(item,index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in this.onlyTabList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action上传图片的url地址 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersOBJ"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">上传图片</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="tabFromList.goods_introduce"></quill-editor>
            <el-button type="primary" class="addGoodsBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览提示框 -->
    <el-dialog title="图片预览" :visible.sync="PicturedialogVisible" width="30%">
      <img :src="previewPic" alt class="previewPic" />
    </el-dialog>
  </div>
</template>

<script>
// 引入拷贝模块
var _ = require("lodash");
export default {
  data() {
    return {
      // 让步骤条跟导航联动 绑定同一个值
      activeIndex: "0",
      //   tab栏中的数据
      tabFromList: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        //   级联选择器 被选中的值得数组
        goods_cat: [],
        // 上传的图片的临时路径
        pics: [],
        // 商品内容
        goods_introduce: "",
        attrs: []
      },
      // tab栏中的数据规则
      tabFromListRules: {
        goods_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur"
          }
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur"
          }
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur"
          }
        ],
        goods_cat: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur"
          }
        ]
      },
      //  分类列表
      cataList: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      //   商品参数列表
      manyTabList: [],
      // 商品静态属性数据列表
      onlyTabList: [],
      // 上传图片的url地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 给上传图片设置请求头 因为组件的内部没有调用axios 所以没有经过拦截器
      headersOBJ: { Authorization: window.sessionStorage.getItem("token") },
      // 图片预览对话框的显示与隐藏
      PicturedialogVisible: false,
      // 图片预览的地址
      previewPic: ""
    };
  },
  methods: {
    //   获取商品分类列表数据
    async getCateList() {
      const { data } = await this.$http.get("categories");
      //   console.log(data);
      if (data.meta.status !== 200) return;
      this.cataList = data.data;
      console.log(this.cataList);
    },
    //   级联选择器选中的节点发生变化时触发 返回选中的节点值
    handleCascaderChange() {
      // 只允许选中三级商品分类
      //   if(this.tabFromList.goods_cat.length!==3){
      //       this.tabFromList.goods_cat=[]
      //   }
      // console.log(this.tabFromList.goods_cat);
    },
    // 切换tabs标签之前的钩子函数 第一个参数是 将要进入的标签 第二个参数是离开的标签
    beforeTabLeave(active, oldActive) {
      if (oldActive === 0 && this.tabFromList.goods_cat !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // 当tab被选中时触发 返回被选中的标签的实例
    async tabClick() {
      // console.log(this.activeIndex);
      if (this.activeIndex === "1") {
        const { data } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (data.meta.status !== 200) {
          return this.$message.error(data.meta.msg);
        }
        this.$message.success(data.meta.msg);
        //   将attr_vals字符串转换为数组
        data.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
        });
        this.manyTabList = data.data;
      } else if (this.activeIndex === "2") {
        const { data } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        if (data.meta.status !== 200) {
          return this.$message.error(data.meta.msg);
        }
        this.$message.success(data.meta.msg);
        this.onlyTabList = data.data;
      }
    },
    // 点击图片名称预效果的函数
    handlePreview(file) {
      console.log(file);
      this.previewPic = file.response.data.url;
      this.PicturedialogVisible = true;
    },
    // 点击图片的删除按钮 处理函数
    handleRemove(response) {
      // 获取到要删除的临时路径
      const removeInfo = { pic: response.response.data.tmp_path };
      // 从pics数组中，找到这个图片对应的索引值
      const i = this.tabFromList.pics.findIndex(i => i.pic === removeInfo);
      this.tabFromList.pics.splice(i, 1);
    },
    // 图片上传成功后调用的钩子函数
    handleSuccess(response) {
      const picInfo = { pic: response.data.tmp_path };
      this.tabFromList.pics.push(picInfo);
    },
    // 确定提交添加商品
    addGoods() {
      // 预校验
      this.$refs.tabFromListRef.validate(async valid => {
        if (!valid) {
          this.$message.error("请填写必要表单内容");
        }
        const tab = _.cloneDeep(this.tabFromList);
        // 将级联选择器选中的数组转换为字符串 但是不能直接进行转换 因为有内容绑定的是这个数组 如果一旦直接改变这个值 就会进行报错 所以应该深拷贝一份 在进行操作
        tab.goods_cat = tab.goods_cat.join(",");

        // 处理商品参数列表
        this.manyTabList.forEach(item => {
          const newinfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          };
          this.tabFromList.attrs.push(newinfo);
        });
        // 处理商品静态属性数据列表
        this.onlyTabList.forEach(item => {
          const newinfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          };
          this.tabFromList.attrs.push(newinfo);
        });
        tab.attrs = this.tabFromList.attrs;
        console.log(tab);
        const { data } = await this.$http.post("goods", tab);
        if (data.meta.status !== 201) {
          return this.$message.error(data.meta.msg);
        }
        this.$message.success(data.meta.msg);
        console.log(data);
        this.$router.push('/goods')
        
      });
    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    //   获取当前分类的id
    cateId() {
      if (this.tabFromList.goods_cat.length === 3) {
        return this.tabFromList.goods_cat[2];
      }
      return null;
    }
  }
};
</script>

<style lang="less" scoped>
.el-cascader {
  width: 50%;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.addGoodsBtn {
  margin-top: 15px;
}
.previewPic {
  width: 100%;
}
</style>